package cn.itcast.nems.approval.service.impl;

import cn.hutool.core.lang.Assert;
import cn.itcast.ic.common.exception.v2.BizExceptionProducer;
import cn.itcast.nems.approval.dao.entity.ApprovalForm;
import cn.itcast.nems.approval.dao.entity.ApprovalFormFlow;
import cn.itcast.nems.approval.dao.mapper.ApprovalFormFlowMapper;
import cn.itcast.nems.approval.dao.mapper.ApprovalFormMapper;
import cn.itcast.nems.approval.enumeration.ApprovalFormFlowNodeEventEnum;
import cn.itcast.nems.approval.model.ApprovalFormFlowAuditDTO;
import cn.itcast.nems.approval.service.ApprovalFormFlowService;
import cn.itcast.nems.common.enumeration.NemsErrorBodyEnum;
import cn.itcast.nems.common.utils.WrapperUtil;
import cn.itcast.nems.studentrecord.constant.ReferenceTypeEnum;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class ApprovalFormFlowServiceImpl extends ServiceImpl<ApprovalFormFlowMapper,ApprovalFormFlow > implements ApprovalFormFlowService {
    private final ApprovalFormMapper approvalFormMapper ;
    @Override
    public void audit(ApprovalFormFlowAuditDTO auditDTO) {
        log.info("【审批】请求参数：{}" , JSON.toJSONString(auditDTO));
        ApprovalForm approvalForm = approvalFormMapper.selectOne(
                                                                new WrapperUtil<ApprovalForm>().limitLaseOne("created_datetime")
                                                                    .eq(ApprovalForm::getJournalId , auditDTO.getJournalId())
                                                                    .eq(ApprovalForm::getJournalType , ReferenceTypeEnum.RENEWAL.name())) ;
        Assert.notNull(approvalForm , BizExceptionProducer.produce(NemsErrorBodyEnum.DATA_EXIST ,"升级凭单ID："+ approvalForm.getJournalId())) ;
        ApprovalFormFlow approvalFormFlow = new ApprovalFormFlow() ;
        approvalFormFlow.setFormId(approvalForm.getId());
        approvalFormFlow.setNodeComment(auditDTO.getNodeComment());
        approvalFormFlow.setNodeEvent(auditDTO.getPassed()? ApprovalFormFlowNodeEventEnum.APPROVED.name() : ApprovalFormFlowNodeEventEnum.REJECTED.name());
        log.info("【审批】需要持久化的流程审批单审批流记录：{}" , JSON.toJSONString(approvalFormFlow));
        int result  = getBaseMapper().insert(approvalFormFlow) ;
        Assert.isTrue(result> 0 ,  BizExceptionProducer.produce(NemsErrorBodyEnum.DATABASE_INSERT_ERROR ,"流程审批单审批流记录"));
    }
    
    
    @Override
    public void inform(String formID, String targetAssignee) {
        ApprovalFormFlow approvalFormFlow = new ApprovalFormFlow() ;
        approvalFormFlow.setFormId(formID);
        approvalFormFlow.setNodeEvent(ApprovalFormFlowNodeEventEnum.INFORMED.name());
        approvalFormFlow.setCreatedBy(targetAssignee);
        getBaseMapper().insert(approvalFormFlow);
    }
}
